//
//  Training.m
//  singlebreath
//
//  Created by Eric van Riet Paap on 21-09-08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "Training.h"


@implementation Training

@synthesize	name, holds;


+(id)trainingWithName:(NSString*)_name holds:(NSMutableArray*)_holds {
	return [[[Training alloc] initWithName:_name holds:_holds] retain];
}


-(id)initWithName:(NSString*)_name holds:(NSMutableArray*)_holds {
	self.name  = _name;
	self.holds = _holds;
	return self;
}


-(int)numberOfHolds {
	return [holds count];
}


-(Hold*)lastHold {
	return [holds objectAtIndex:[self numberOfHolds] - 1];
}


-(float)duration {
	if ([self numberOfHolds] == 0) {
		return 0.0;
	}
	return [self lastHold].end;
}


-(Hold*)holdAtTime:(float)atTime {
	NSEnumerator	*enumerator = [holds objectEnumerator];
	Hold			*hold;
	while ((hold = [enumerator nextObject])) {
		if (atTime >= hold.begin && atTime < hold.end) {
			return hold;
		}
	}
	return nil;
}


-(float)phaseRangeAtTime:(float)atTime phase_end:(float*)phase_end {
	float			t = 0.0;
	NSEnumerator	*enumerator = [holds objectEnumerator];
	Hold			*hold;
	while ((hold = [enumerator nextObject])) {
		if (atTime >= t && atTime < hold.begin) {
			*phase_end = hold.begin;
			return t;
		}
		if (atTime >= hold.begin && atTime < hold.end) {
			*phase_end = hold.end;
			return hold.begin;
		}
		t = hold.end;
	}
	NSLog(@"Error: phaseRangeTimeAtTime atTime not found");
	*phase_end = 0.0;
	return 0.0;	
}


-(NSString*)asString {
	NSMutableString *s = [[[NSMutableString alloc] init] autorelease];
	int				n  = 0;
	
	//[s appendFormat:@"Training: %@ (duration %02d:%02d)", name, (int)[self duration] / 60, (int)[self duration] % 60];
	[s appendFormat:@"%@", name];
	
	NSEnumerator	*enumerator = [holds objectEnumerator];
	Hold			*hold;
	while ((hold = [enumerator nextObject])) {
		int	b = (int)hold.begin;
		int	e = (int)hold.end;
		[s appendFormat:@"\n   %2d. %d:%02d-%d:%02d (%d:%02d)", ++n, b / 60, b % 60, e / 60, e % 60, (e - b) / 60, (e - b) % 60];
	}
	
	return s;
}

-(NSString*)asHTML {
	NSMutableString *s = [[[NSMutableString alloc] init] autorelease];
	int				n  = 0;
	
	//[s appendFormat:@"<body bgcolor='black' text='white'><b><center>Training: %@ (duration %02d:%02d)</center></b>", name, (int)[self duration] / 60, (int)[self duration] % 60];
	[s appendFormat:@"<body bgcolor='black' text='white'><b><center>%@</center></b>", name];
	
	NSEnumerator	*enumerator = [holds objectEnumerator];
	Hold			*hold;
	while ((hold = [enumerator nextObject])) {
		int	b = (int)hold.begin;
		int	e = (int)hold.end;
		[s appendFormat:@"<br>&nbsp;&nbsp;&nbsp;%2d. %d:%02d-%d:%02d (%d:%02d)", ++n, b / 60, b % 60, e / 60, e % 60, (e - b) / 60, (e - b) % 60];
	}
	
	[s appendFormat:@"</body>"];
	return s;
}


@end
